var recorderManager = null;

import play from 'dingtalk-jsapi/api/device/audio/play';
import stop from 'dingtalk-jsapi/api/device/audio/stop';
import pause from 'dingtalk-jsapi/api/device/audio/pause';
import resume from 'dingtalk-jsapi/api/device/audio/resume';
import download from 'dingtalk-jsapi/api/device/audio/download';
import util from "/common/js/util.js";
import Qs from "qs";
/**
  {mediaId: "@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA", remoteUrl: "https://static.dingtalk.com/media/lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA.ogg", duration: 2.46}
 */

var innerAudioContext = dd.getBackgroundAudioManager();
var recorderManager = dd.getRecorderManager();
var fs = dd.getFileSystemManager();

const pageSize = 5;
var Timeout = null;
var Timeout2 = null;
var time_obj = {};
var item_timeout = null;
var app = getApp();
const base_residueTime = 300 //297
const base_residueTimeLength = "4:59";
var mediaData = {};

// recorderManager.onstop = (res) => {
//   console.log(res);
//   dd.alert({ content: JSON.stringify(res) });
// };


// recorderManager.start({ duration: 10, frameSize: 50 });

// recorderManager.onstart({
//     success: (res) => {
//       console.log(res);
//     },
//     fail: () => {},
//     complete: () => {},
//   });

Page({
  data: {
    scrollTop: 0,
    toView: "",
    btnStatus: "stop",
    payIng: false, //红灯闪烁
    plays:[
      {remoteUrl: "https://resource/26ee88f3f997166a7fe1991a762ab9d.audio", duration: "11700",play:false,title:"标题1",
      "bookId": "1811641576373571585",
      "bookName": "恒丽哲学手册",
      "userId": "2363192520970306",
      "userName": "刘庆峰",
      "chapter": "哲学原点",
      "note": "",
      "pageNum": null,
      "startPage": 13,
      "endPage": 14,
      "createTime": "2024-08-01 18:50:42",

    },
      {remoteUrl: "https://resource/dedb4878188c86fc7de3ece43bc994ef.audio", play: false, duration: 77940,title:"标题2", timeLength: "01:17",
      "bookId": "1811641576373571585",
      "bookName": "恒丽哲学手册",
      "userId": "2363192520970306",
      "userName": "刘庆峰",
      "chapter": "哲学原点",
      "note": "",
      "pageNum": null,
      "startPage": 13,
      "endPage": 14,
      "createTime": "2024-08-01 18:50:42",

    },
      {remoteUrl: "https://resource/26ee88f3f997166a7fe1991a762ab9d.audio", duration: "11700",play:false,title:"标题3",
      "bookId": "1811641576373571585",
      "bookName": "恒丽哲学手册",
      "userId": "2363192520970306",
      "userName": "刘庆峰",
      "chapter": "哲学原点",
      "note": "",
      "pageNum": null,
      "startPage": 13,
      "endPage": 14,
      "createTime": "2024-08-01 18:50:42",

    },
      {remoteUrl: "https://resource/dedb4878188c86fc7de3ece43bc994ef.audio", play: false, duration: 77940,title:"标题4", timeLength: "01:17",
      "bookId": "1811641576373571585",
      "bookName": "恒丽哲学手册",
      "userId": "2363192520970306",
      "userName": "刘庆峰",
      "chapter": "哲学原点",
      "note": "",
      "pageNum": null,
      "startPage": 13,
      "endPage": 14,
      "createTime": "2024-08-01 18:50:42",

    }
    ],//新数组
    recordAudioArr: [
      // {
      //   "noteId": "1818840747596226562",
      //   "bookId": "1811641576373571585",
      //   "bookName": "恒丽哲学手册",
      //   "userId": "2363192520970306",
      //   "userName": "刘庆峰",
      //   "chapter": "哲学原点",
      //   "note": "",
      //   "pageNum": null,
      //   "startPage": 13,
      //   "endPage": 14,
      //   "mediaId": "@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA",
      //   remoteUrl: "http://220.161.77.66:10111/app_file/mp3/2024-08-22/lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA.mp3",
      //   // remoteUrl: "https://static.dingtalk.com/media/lR_PD3CL9vhuXDcAALCCqlmJpSfbewaclM-aJ9UA.ogg",     
      //   "duration": 279.9,
      //   "roundDuration": 280,
      //   "isDelete": 0,
      //   "createTime": "2024-08-01 10:46:41",
      //   "updateTime": "2024-08-01 10:46:41",
      //   "formatDate": "2024-08-01",
      //   "time": "10:46:41",
      //   "timeLength": "04:59"
      // },
      // {
      //   "noteId": "1818840748271509506",
      //   "bookId": "1811641576373571585",
      //   "bookName": "恒丽哲学手册",
      //   "userId": "2363192520970306",
      //   "userName": "刘庆峰",
      //   "chapter": "哲学原点 o1",
      //   "note": "",
      //   "pageNum": null,
      //   "startPage": 13,
      //   "endPage": 14,
      //   "mediaId": "@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA",
      //   "remoteUrl": "http://www.liuqingfeng.top/video/o1.mp3" ,
      //   "duration": 279.9,
      //   "roundDuration": 280,
      //   "isDelete": 0,
      //   "createTime": "2024-08-01 10:46:41",
      //   "updateTime": "2024-08-01 10:46:41",
      //   "formatDate": "2024-08-01",
      //   "time": "10:46:41",
      //   "timeLength": "00:02"
      // },
      // {
      //   "noteId": "1818852212160004098",
      //   "bookId": "1811641576373571585",
      //   "bookName": "恒丽哲学手册",
      //   "userId": "2363192520970306",
      //   "userName": "刘庆峰",
      //   "chapter": "哲学原点",
      //   "note": null,
      //   "pageNum": null,
      //   "startPage": 10,
      //   "endPage": 11,
      //   "mediaId": "@lR_PM39RSueWI6MAALDt0WcPMHvg6AaUnfISOuAA",
      //   "remoteUrl": "https://static.dingtalk.com/media/lR_PM4jeA9jVT6cAALB4VfQAQhv-sAacViLGB5AA.ogg",
      //   "duration": 188.16,
      //   "roundDuration": 188,
      //   "isDelete": 0,
      //   "createTime": "2024-08-01 11:32:14",
      //   "updateTime": "2024-08-01 11:32:14",
      //   "formatDate": "2024-08-01",
      //   "time": "11:32:14",
      //   "timeLength": "00:13"
      // },
      // {"remoteUrl":"https://resource/8c75aa10fc68a3933763d241edd995d3.audio","duration":300180,"createTime":"2024-08-08 10:21:44","userId":"2363192520970306","userName":"刘庆峰","chapter":"哲学原点","note":"","startPage":13,"endPage":14},

      // {"remoteUrl":"https://resource/5cd41c06e487ec9d0e10abfb5f46261b.audio","duration":14000,"createTime":"2024-08-08 11:24:53","userId":"2363192520970306","userName":"刘庆峰","chapter":"哲学原点","note":"","startPage":13,"endPage":14},
      // {"remoteUrl":"https://resource/95db300b3ff5d4239f3a2b3a3d13aa8b.audio","duration":18000,"createTime":"2024-08-08 11:49:08","userId":"2363192520970306","userName":"刘庆峰","chapter":"哲学原点","note":"","startPage":13,"endPage":14}


    ], // 音频文件数组

    mediaData: null,
    startTime: 0,
    timeLength: "00:00", //显示录制时长
    residueTime: base_residueTime, //倒计时 秒
    residueTimeLength: base_residueTimeLength, //剩余录制时间
    queryData: {},
    page: 1,
    pageSize: pageSize,
    showLoadMore: false,
    showLoadMoreTxt: "over",
    totalResult: pageSize,
    view: false, //查看模式
    loginUserId: "", //当前登录人员id
    dataList: {},
    enableNative: false,
    isStop:false,// 是否完全停止

    basicVisible:false,
    platform:""
  },
  onLoad(e) {
    // console.log("-进入");
    // console.log(e);
    let loginUserId = app.prototype.$userId;
    this.setData({
      queryData: e,
      loginUserId
    });
    let view = false;
    if (loginUserId == e.userId) {
      view = false;
    } else {
      view = true;
    }
    this.setData({
      view,
      unSubmitArr: []
    });

    dd.getSystemInfo({
      success: (res) => {
        // res.platform;
        console.log("--res.platform", res.platform);
        this.setData({
          platform:res.platform
        })
        if (res.platform == "iOS") {
          this.setData({
            enableNative: true
          })
        }
      }
    })

    // if (app.prototype.$userName == "刘庆峰") {
    //   this.setData({
    //     enableNative:true
    //   })
    // }


    this.initFn();

    const updateManager = dd.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      if (res.hasUpdate) {
        updateManager.onUpdateReady(function (ret) {
          //console.log(ret.version) // 更新版本号
          dd.confirm({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success: function (res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate()
              }
            }
          })
        })
      }
    })


    // dd.getAuthCode({
    //   success: function (res) {
    //     console.log(res);
    //   }
    // });
    // this.showIntegralIcon();

    //  recorderManager = dd.getRecorderManager ();

    recorderManager = dd.getRecorderManager();

    recorderManager.onerror = (res) => {
      console.log("--error");
      console.log(res);
    };


    recorderManager.onframerecorded = (res) => {
      console.log('----录制完成::', JSON.stringify(res));
      // console.log('onFrameRecorded arraybuffer', JSON.stringify(res.frameBuffer));
    };

    recorderManager.onstart= (res) => {
      this.runThread();
    }
    
    // recorderManager.onstop({
    //   success:(res)=>{
    //     console.log("--success:",res);
    //   },
    //   fail: () => {},
    //   complete:(res)=>{
    //     console.log("--complete:",res);

    //   }
    // })
    

    recorderManager.onstop = (res) => {

     console.log("----原文件",res);
      let recordAudioArr = this.data.recordAudioArr;
      let that=this;
      let platform=this.data.platform;

      fs.saveFile({
        tempFilePath: res['tempFilePath'],
        success: function (hh) {
       //  console.log("---得到录音文件:", hh);
          let duration=parseInt(res.duration);

          let m=duration/1000;
          let json = {
            remoteUrl: hh.savedFilePath,
            platform,
            duration,
          }

          // console.log("--json:",JSON.stringify(json));
          // recordAudioArr.push(json);
          // that.setData({
          //   recordAudioArr
          // });
          that.submitFn(json);
         // that.zero_audio.initF();
          console.log("---isStop:",that.data.isStop);
          if(!that.data.isStop){
            that.startRecordFn();
          }

        },
        fail: function (hh) {
          // dd.alert({
          //   content: 'recorder saveFile fail' + JSON.stringify(hh)
          // });
        },
        complete: function (hh) {
          // dd.alert({
          //   content: 'recorder saveFile complete' + JSON.stringify(hh)
          // });
        },
      });
      
      
      // let json={
      //   remoteUrl:res.tempFilePath
      // }
      // recordAudioArr.unshift(json);
      this.setData({
        btnStatus: "stop"
      })
    };


    
  },
  onShow() {},
  getIsLogin() {
    this.tableList()
  },
  zero_audio(ref){
    this.zero_audio=ref
  },
  startItem(e, that) {
    let arr = e.currentTarget.dataset.arr;
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    let list = this.data[arr];
    let item = list[index];
    let startTime = item.startTime;
    // item.duration2=item.duration;
    let duration = item.duration2;
    list.forEach(row => {
      if (row.mediaId == id) {
        row.play = true;
        row.startTime = 0;
        row.duration2 = row.duration;
        // let duration=row.duration2;
      } else {
        row.play = false;
        row.timeLength = that.format(row.duration);
      }
    })



    // item.timeLength="00:00";
    // console.log("list",list);
    that.setData({
      [`${arr}`]: list
    });


    // let time_id=setInterval(() => {
    //   startTime= startTime+1 ;
    //   let timeLength=that.format(startTime);
    //   item.timeLength=timeLength;
    //   duration=duration-1;
    //   item.duration2=duration;
    //   that.setData({
    //     [`${arr}`]:list
    //   });

    //   if(duration==0){
    //     clearInterval(time_id)
    //   }

    // }, 1000);
    // time_obj[id]=time_id;
    // console.log("--time_id",time_obj);
  },
  submitFn(obj){
    let api = "/user/book/addTestNote";
    app.$post(api, obj).then(res => {
     
      if (res.code == 200) {

      this.searchFn();

      } else {
        util.message(res.message);

      }
    })

  },
  //旧播放
  playFn(e) {
    let arr = e.currentTarget.dataset.arr;
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    let list = this.data[arr];
    let item = list[index];
    // console.log("--item:",item);
    let that = this;

    download({
      mediaId: id,
      success: (suc) => {
        console.log("--suc", suc);
        if (item.play == undefined) {
          play({
            localAudioId: suc.localAudioId,
            success: (ms) => {
              that.startItem(e, that)
            },
            fail: (e) => {
              console.log("--错误", e);
            },
            complete: () => {},
          });
        }
        if (item.play == undefined) {
          that.startItem(e, that);
        }
        if (item.play) {

          pause({
            localAudioId: suc.localAudioId,
            success: (ms) => {
              item.play = false;
              item.timeLength = that.format(item.duration);
              that.setData({
                [`${arr}`]: list
              })

            },
            fail: (e) => {
              // console.log("--错误",e);
            },
            complete: () => {},
          })
        }


      },
      fail: () => {},
      complete: () => {},
    });

  },

  //新播放
  playFn2(e){
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    let list = this.data.plays;
    let item = list[index];
    let bam = dd.getBackgroundAudioManager();//背景音频管理器
    bam.onError = (err) => {
      dd.showToast({content: JSON.stringify(err)});
    }
    // let idx = e.currentTarget.dataset.idx;//录音的索引
    bam.src = item.url;
    bam.title = '测试标题';//不实例化此属性，ios调用多次play()，playbackRate会累加
    bam.coverImgUrl = "https://img.alicdn.com/tps/TB1sXGYIFXXXXc5XpXXXXXXXXXX.jpg"
    bam.play();
  },
  playFn3(e){
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    let arr = e.currentTarget.dataset.arr;

    let list = this.data[arr];
    let item = list[index];
    let bam = dd.getBackgroundAudioManager();//背景音频管理器
    bam.onError = (err) => {
      dd.showToast({content: JSON.stringify(err)});
    };
    // let idx = e.currentTarget.dataset.idx;//录音的索引
    // remoteUrl
    console.log("----remoteUrl::",remoteUrl);
    bam.src = item.remoteUrl;
    bam.title = '测试标题';//不实例化此属性，ios调用多次play()，playbackRate会累加
    bam.coverImgUrl = "https://img.alicdn.com/tps/TB1sXGYIFXXXXc5XpXXXXXXXXXX.jpg"
    // bam.play();
    // debugger
  },
  format(seconds) { //秒转化为分钟格式
    let s = Math.trunc(seconds);
    let minInt = Math.floor(s / 60);
    let min = minInt >= 10 ? minInt : '0' + minInt;
    s -= 60 * min;
    let sec = s >= 10 ? s : '0' + s;
    return min + ':' + sec;
  },
  resetFn() {
    //重置参数
    this.setData({
      timeLength: "0:00",
      startTime: 0,
      payIng: false,
      residueTimeLength: util.copy(base_residueTimeLength),
      residueTime: util.copy(base_residueTime)
    })

  },
  onDeleteFn(e){
    console.log("--删除:",e);
  },
  testFn(){
   // this.zero_audio0.onAcceptNotifyMsg("嘿嘿")
  //  const myComponent = this.$selectComponent(".my-component-class");
  //  console.log(myComponent);
  // this[`zero_audio0`].onAcceptNotifyMsg("嘿嘿")
    let url ="";
//    url = "https://liuqingfeng-read-buket.oss-cn-shenzhen.aliyuncs.com/file/2024-08-26/%E3%80%8A%E6%B5%B7%E5%85%B3%E9%AB%98%E7%BA%A7%E8%AE%A4%E8%AF%81%E4%BC%81%E4%B8%9A%E6%A0%87%E5%87%86%E3%80%8B%EF%BC%88%E5%8D%95%E9%A1%B9%E6%A0%87%E5%87%86%EF%BC%89.doc";
//    url="https://liuqingfeng-read-buket.oss-cn-shenzhen.aliyuncs.com/file/2024-08-26/%E4%B8%AD%E5%8D%8E%E4%BA%BA%E6%B0%91%E5%85%B1%E5%92%8C%E5%9B%BD%E4%BC%9A%E8%AE%A1%E6%B3%95%EF%BC%882024%E5%B9%B4%EF%BC%89.pdf";
//    url ="http://test.liuqingfeng.top:10111/app_file/images/2024-08/2024-08-26/%E4%B8%AD%E5%8D%8E%E4%BA%BA%E6%B0%91%E5%85%B1%E5%92%8C%E5%9B%BD%E4%BC%9A%E8%AE%A1%E6%B3%95%EF%BC%882024%E5%B9%B4%EF%BC%89.pdf"
    url ="http://220.161.77.66:10111/app_file/images/2024-08/2024-08-26/%E4%B8%AD%E5%8D%8E%E4%BA%BA%E6%B0%91%E5%85%B1%E5%92%8C%E5%9B%BD%E4%BC%9A%E8%AE%A1%E6%B3%95%EF%BC%882024%E5%B9%B4%EF%BC%89.pdf"
    let str = url.replaceAll("https://liuqingfeng-read-buket.oss-cn-shenzhen.aliyuncs.com/file/", "");
    let arr = str.split(".");
    let FILE_TYPE = arr[arr.length-1];
    let data = {
      url,
      FILE_TYPE
    };
    console.log(data);
    let p = Qs.stringify(data);
    let path = '/pages/web_view/file_view/file_view';
    let to_url = `${path}?${p}`;
    dd.navigateTo({
      url: to_url
    })
  },
  testFn2(){
    let info=
    "{\"modifiedTime\":\"Thu Aug 29 15:24:05 CST 2024\",\"extension\":\"pdf\",\"creatorId\":\"FiimGbp9iiajIiE\",\"modifierId\":\"FiimGbp9iiajIiE\",\"type\":\"FILE\",\"partitionType\":\"PUBLIC_OSS_PARTITION\",\"uuid\":\"Amq4vjg890LOMnbxhLKOA4EDJ3kdP0wQ\",\"version\":2,\"parentId\":\"0\",\"path\":\"/卓越绩效评价准则GBT 19580 2012.pdf\",\"spaceId\":\"24904995948\",\"size\":662825,\"createTime\":\"Thu Aug 29 15:05:31 CST 2024\",\"storageDriver\":\"DINGTALK\",\"name\":\"卓越绩效评价准则GBT 19580 2012.pdf\",\"id\":\"151314331642\",\"properties\":{\"readOnly\":false},\"appProperties\":{\"NV5HqZsw9FeHiS0aW1LfvZIGoNw8IYPxs\":[{\"visibility\":\"PUBLIC\",\"name\":\"属性1\",\"value\":\"属性值1\"}]},\"status\":\"NORMAL\"}";
    let json=JSON.parse(info);
    dd.previewFileInDingTalk({
      fileId: json.id,
      spaceId: json.spaceId,
      fileName: json.name,
      fileSize: json.size,
      fileType: json.extension,
      success: (e) => {},
      fail: (err) => {
        console.log("---err::",err);
      },
      complete: (e) => {},
    });
  },

  runThread(){
    let that=this;
    Timeout=setInterval(() => {
      let payIng=that.data.payIng;
      let startTime=that.data.startTime;
      startTime= startTime+1 ;
      let timeLength=that.format(startTime);
      let residueTime=that.data.residueTime;
      residueTime=residueTime-1;
      let residueTimeLength=that.format(residueTime);
      that.setData({
        startTime,
        residueTime,
        timeLength,
        residueTimeLength,
        payIng:!payIng
      });
      if(residueTime==0){
        console.log("--自动停止录音");
        that.autoStopRecordFn();
      }else{
        // if(app.prototype.$userName=="刘庆峰"){
        //   that.testGet();
        // }
      }
      
    }, 1000);
  },
  autoStopRecordFn(){
    let that=this;
    clearTimeout(Timeout);
    this.resetFn();
  },

  initFn() {

    this.getIsLogin();
    //  this.showIntegralIcon2()
  },
  tableList(obj) {
    let api = "/user/book/testNoteList";
    let list = {
      page: this.data.page,
      pageSize: this.data.pageSize,
    };
    // if(obj){
    //   list=util.mergeObj(list,obj)
    // }
    // console.log("--list:",list);
    let that = this;
    this.setData({
      showLoadMoreTxt: "load"
    });


    dd.showLoading({
      content: '数据加载中...',
    })
    let dataList = this.data.recordAudioArr;

    app.$post(api, list).then(res => {
      dd.stopPullDownRefresh()
      dd.hideLoading();
      if (res.code == 200) {

        let arr_list = dataList.concat(res.data.list);
        arr_list.forEach(r => {

          r.timeLength = this.format(r.duration/1000)
        })
        let page = this.data.page;
        page = page + 1;
        console.log(arr_list);
        this.setData({
          totalResult: res.data.totalResult,
          page,
          recordAudioArr: arr_list,
          showLoadMoreTxt: "over"
        });
       

      } else {
        util.message(res.message);

      }
    })
  },

  onPullDownRefresh() {
    // 页面被下拉
    this.setData({
      showLoadMoreTxt: "load"
    });
    // this.searchFn();
  },
  searchFn(obj) {
    this.setData({
      page: 1,
      pageSize,
      recordAudioArr: []
    });
    this.tableList(obj)
  },
  onScrollToLower() {
    // console.log("---触底了!");
    this.tableList()
  },


  testGet() {
    dd.alert({
      title: '消息提示',
      content: JSON.stringify(mediaId),
      buttonText: '我知道了',
      success: () => {},
      fail: () => {},
      complete: () => {},
    });
  },


  bindKeyInput(e) {
    let key = "queryData.note";
    // util.debounce(() => {

    // }, 300);
    this.setData({
      [`${key}`]: e,
    });
  },

  onShareAppMessage() {

    let p = Qs.stringify(this.data.queryData);
    let path = '/pages/note/noteView/noteView';
    let url = `${path}?${p}`;
    return {
      title: '恒丽书城',
      desc: `${this.data.dataList.userName}的读书笔记`,
      path: url,
    };
  },
  startFn(){
    this.setData({
      isStop:true
    })
    this.startRecordFn();
  },
  //录音测试
  startRecordFn() {

    try {
    //  frameSize: 50

      recorderManager.start({
        duration: 300,
        frameSize: 100,
        format:"mp3",
      });
      this.setData({
        btnStatus: "start"
      })
    } catch (error) {
      console.log(error);
    }

  },
  stopFn(){
    this.setData({
      isStop:true
    })
    this.stopRecordFn()
  },
  stopRecordFn() {
    // debugger
    
    recorderManager.stop();

  },


  handleTapLink(){
    this.setData({
      basicVisible:true
    });
  },
  handleClose() {
    this.setData({
      basicVisible:false
    })
  }
});